package com.choudou5.tools.excel.luowei;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.choudou5.tools.excel.BasicExcelHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class LwExcelMergeCellDemo extends BasicExcelHelper {

    static String FILE_BASE_PATH = "E://data//";

    public static void main(String[] args) throws Exception {
        String filePath = FILE_BASE_PATH+ "工作簿2(1).xlsx";
        List<List<Object>> list = readData(filePath, 0);
        List<Map> newList = formatData(list);
        //打印
//        printData(newList);
        //输出文件
        wirteFile("新文件012345.xlsx", newList);
    }

    private static List<Map> formatData(List<List<Object>> list){
        List<Map> newList = new ArrayList();
        Map map = null;
        String lastTitle = null;
        for (List<Object> row : list) {
//            System.out.println(JSON.toJSONString(row));
            String firstCell = row.get(0).toString();
            if(StrUtil.isNotBlank(firstCell)) {
                if(lastTitle != null)
                    newList.add(map);
                lastTitle = firstCell;
                map = new LinkedHashMap();
                map.put("title", firstCell);
                map.put("value", row.get(1));
            }else{
                if(row.size() == 1){
                    if(lastTitle != null)
                        newList.add(map);
                    Map blank = new LinkedHashMap();
                    blank.put("title", "");
                    blank.put("value", "");
                    newList.add(blank);
                    lastTitle = null;
                    continue;
                }
                if(lastTitle != null){
                    map.put("value", map.get("value")+""+row.get(1));
                }
            }
        }
        if(map != null){ //处理最后一个
            newList.add(map);
        }
        return newList;
    }

    private static void wirteFile(String newFileName, List<Map> newList){
        File newFile = new File(FILE_BASE_PATH+newFileName);
        ExcelWriter writer = ExcelUtil.getWriter(newFile);
        Map<String, String> headerAlias = new LinkedHashMap<>();
        headerAlias.put("title", "标题");
        headerAlias.put("value", "说明");
        writer.setHeaderAlias(headerAlias);
        writer.write(newList);
        writer.flush();
        writer.close();
    }


}
